package com.kingmed.kmss.auth.api;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.kingmed.kmss.common.annotation.IgnoreCommonResponseAdvice;
import com.kingmed.kmss.common.dto.admin.ums.AdminDTO;
import com.kingmed.kmss.common.dto.api.resp.admin.TokenAuthUserVo;
import com.kingmed.kmss.common.exception.InternalApiException;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;
import com.kingmed.kmss.framework.feign.client.admin.CommonAdminFeignServiceFacade;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 对外围系统提供的标准接口
 * 强制：只能调用framework-feign里的client，不允许添加任何业务逻辑，业务逻辑必须写在facade
 * </p>
 */
@RestController
@RequestMapping("/ext/auth")
@Api(tags = "系统管理-对外标准接口")
@IgnoreCommonResponseAdvice
public class AuthClientController {

    private static final String TOKEN_ERROR_MSG = "Token无效";

    @Autowired
    private CommonAdminFeignServiceFacade adminFeignServiceFacade;

    /**
     * 校验token是否生效
     */
    @ApiOperation(value = "校验token是否生效")
    @GetMapping(value = "/checkToken")
    public CommonResponse<TokenAuthUserVo> checkToken(@RequestParam String token) {
        if (StrUtil.isBlank(token)) {
            throw new InternalApiException("Token不能为空");
        }
        Object obj = StpUtil.getLoginIdByToken(token);
        if (obj == null) {
            throw new InternalApiException(TOKEN_ERROR_MSG);
        }
        String loginIdStr = obj.toString();
        String loginId = loginIdStr.substring(loginIdStr.indexOf(":") + 1);
        if (StrUtil.isBlank(loginId)) {
            throw new InternalApiException(TOKEN_ERROR_MSG);
        }
        AdminDTO result = adminFeignServiceFacade.queryUserById(loginId);
        if (result == null || StrUtil.isBlank(result.getUsername())) {
            throw new InternalApiException(TOKEN_ERROR_MSG);
        }
        return CommonResponseHelper.success(new TokenAuthUserVo(result.getUsername(), result.getEmployeeNum()));
    }

}
